<?php
/**
 * 卡券相关服务
 * User: poptser@foxmail.com
 * Date: 2018/1/26
 * Time: 16:11
 */
namespace App\Services\Bonus;

use App\Repositories\MoneyCard\CardCouponsClassRepositoryEloquent;
use App\Repositories\MoneyCard\CardCouponsRepositoryEloquent;
use App\Repositories\Users\UsersRepositoryEloquent;

class CardCoupons{

    protected $cardCoupons;
    protected $cardClass;
    protected $userInfo;
    protected $userId;

    public function __construct(
                    CardCouponsRepositoryEloquent $cardCoupons,
                    CardCouponsClassRepositoryEloquent $cardClass,
                    UsersRepositoryEloquent $userInfo
            ){
        $this->cardClass = $cardClass;
        $this->cardCoupons = $cardCoupons;
        $this->userInfo = $userInfo;
        $this->userId = 1;
    }

    public function useCard(string $cardSn){
        $cardInfo = $this->getCardInfo($cardSn);
        if($cardInfo){
            if($cardInfo['user_id']>0){
                return ['error'=>1,'msg'=>'this sn is used !'];
            }else{
                $classClass = $this->getCardClass($cardInfo['id']);
                $canUse = $this->checkCardUse($cardInfo,$classClass);
                if($canUse===true){
                    //准备使用卡券
                }else{
                    //不能使用
                    return $canUse;
                }
            }
        }else{
            //此卡券未找到
            return ['error'=>1,'msg'=>'this sn not found !'];
        }
    }


    /**
     * 获取卡券列表 【 已使用 】
     */
    public function getCardList(){

    }

    /**
     * 获取卡券详情
     * @param string $cardSn
     * @return bool|mixed
     */
    public function getCardInfo(string $cardSn){
        return $this->cardCoupons->getCardCouponsInfo($cardSn);
    }

    /**
     * 获取卡券类型
     * @param int $id
     */
    public function getCardClass(int $id){
        $this->cardClass->getCardCouponsClassInfo($id);
    }

    public function checkCardUse(array $card,array $cardClass){
        if($cardClass['astrict']==0&&$card['is_vip']==0){
            return true;    //未开启充值限制和用户等级限制
        }
        if($cardClass['is_vip']!=0){
            //已开启用户等级限制
            $user_rank = $this->userInfo->getUserRankByUid($this->userId);
            if($cardClass['is_vip']!=$user_rank){
                return ['error'=>1,'msg'=>'user level is err !'];
            }
        }

        if ($cardClass['astrict']!=0){
            if($cardClass['astrict']>$this->cardCoupons->countCardUsed($cardClass['id'],$this->userId)){
                return true;
            }else{
                return ['error'=>1,'msg'=>'The number of recipients has reached the limit !'];
            }
        }

    }
}